package com.lzh.hosp.controller;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzh.hosp.common.Const;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.SysRole;
import com.lzh.hosp.model.SysRoleMenu;
import com.lzh.hosp.model.SysUserRole;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/role")
@Tag(name = "角色管理")
public class SysRoleController extends BaseController {
   @GetMapping("/info/{id}")
   @PreAuthorize("hasAuthority('sys:role:list')")
   public ResponseResult info(@PathVariable Long id) {
      SysRole role = sysRoleService.getById(id);
      List<SysRoleMenu> roleMenus = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
      List<Long> menuIds = roleMenus.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
      role.setMenuIds(menuIds);
      return ResponseResult.ok(role);
   }

   @GetMapping("/list")
   @PreAuthorize("hasAuthority('sys:role:list')")
   public ResponseResult list(String name) {
      Page<SysRole> roles = sysRoleService.page(getPage(),
            new QueryWrapper<SysRole>()
                  .like(StringUtils.isNotBlank(name), "name", name)
      );
      return ResponseResult.ok(roles);
   }

   @PostMapping("/save")
   @Operation(summary = "保存角色")
   @PreAuthorize("hasAuthority('sys:role:save')")
   public ResponseResult save(@Validated @RequestBody SysRole sysRole) {
      sysRole.setCreated(LocalDateTime.now());
      sysRole.setStatu(Const.STATUS_ON);
      sysRoleService.save(sysRole);
      return ResponseResult.ok(sysRole);
   }

   @PostMapping("/update")
   @Operation(summary = "修改角色")
   @PreAuthorize("hasAuthority('sys:role:update')")
   public ResponseResult update(@Validated @RequestBody SysRole sysRole) {
      sysRole.setUpdated(LocalDateTime.now());
      sysRoleService.updateById(sysRole);
      return ResponseResult.ok(sysRole);
   }

   @Transactional
   @PostMapping("/delete")
   @Operation(summary = "删除角色")
   @PreAuthorize("hasAuthority('sys:role:delete')")
   public ResponseResult delete(@RequestBody Long[] ids){
      sysRoleService.removeByIds(Arrays.asList(ids));
      // 同步删除
      sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));
      sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));
      return ResponseResult.ok();
   }

   @Transactional
   @Operation(summary = "授权")
   @PostMapping("/perm/{roleId}")
   @PreAuthorize("hasAuthority('sys:role:perm')")
   public ResponseResult perm(@PathVariable Long roleId, @RequestBody Long[] menuIds) {
      List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
      Arrays.stream(menuIds).forEach(menuId -> {
         SysRoleMenu roleMenu = new SysRoleMenu();
         roleMenu.setMenuId(menuId);
         roleMenu.setRoleId(roleId);
         sysRoleMenus.add(roleMenu);
      });

      sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));

      sysRoleMenuService.saveBatch(sysRoleMenus);

      // 清除所有用户的权限缓存信息
      sysUserService.clearUserAuthorityInfoByRoleId(roleId);
      return ResponseResult.ok(menuIds);
   }
}